﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;


namespace QuickExcel
{
    public partial class ExportRangeAsGraphics : Form
    {
        public ExportRangeAsGraphics()
        {
            InitializeComponent();
            txtRange.Text = Globals.ThisAddIn.Application.Selection.Address;
        }

        private void cmdCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtRange_Click(object sender, EventArgs e)
        {
            Excel.Range rng;
            rng = Globals.ThisAddIn.Application.InputBox("Please select range", "Select Range", txtRange.Text, this.Left - 5, this.Top + 5, Type: 8);
            rng.Select();
            txtRange.Text = rng.Address;
            this.Activate();
        }

        private void cmdOK_Click(object sender, EventArgs e)
        {
            string filename="temp", ext = "gif";

            if (opGif.Checked)
                ext = "gif";
            else if (opJpeg.Checked)
                ext = "jpg";
            else if (opPng.Checked)
                ext = "png";
            else if (opTif.Checked)
                ext = "tif";
           
            Excel.Range rng = Globals.ThisAddIn.Application.ActiveSheet.Range(txtRange.Text);
            Excel.ChartObject chrt = Globals.ThisAddIn.Application.ActiveSheet.ChartObjects.Add(50, 32, rng.Width, rng.Height);
            rng.Cells[1,1].Select();
            
            if (rng.Areas.Count > 1)
            {
                System.Windows.Forms.MessageBox.Show("This addin didn't work with multiple areas");
                this.Close();
            }
            
            saveFileDialog.ShowDialog();
            filename = saveFileDialog.FileName;
            filename = filename + "." + ext;
            rng.Cells[1, 1].Select();

            rng.Copy();
            Globals.ThisAddIn.Application.ActiveSheet.Pictures.Paste().Select();

            Globals.ThisAddIn.Application.Selection.Copy();

            Globals.ThisAddIn.Application.ActiveSheet.Pictures.Delete();

            chrt.Chart.Paste();

            chrt.Activate();
            chrt.Chart.Export(filename);

            chrt.Delete();
           
            this.Close();
        }
        
    }
}
